package cn.qiguai.sphapi.service.impl;

import cn.qiguai.sphapi.controller.request.PageSearchGoodsParam;
import cn.qiguai.sphapi.controller.response.Page;
import cn.qiguai.sphapi.domain.*;
import cn.qiguai.sphapi.mapper.GoodsMapper;
import cn.qiguai.sphapi.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
	@Autowired
	private GoodsMapper goodsMapper;

	@Override
	public List<GoodsCategory> getCategoryList() {
		List<GoodsCategory> allCategory = goodsMapper.selectAllCategory();
		Map<Integer, GoodsCategory> categoryMap = new HashMap<>();
		Map<Integer, List<GoodsCategory>> parentChildMap = new HashMap<>();

		// 构建分类映射和父子级映射
		for (GoodsCategory category : allCategory) {
			category.setChild(new ArrayList<>());
			categoryMap.put(category.getId(), category);

			int parentId = category.getParentId();

			/*
			V getOrDefault(Object key, V defaultValue)
			用于获取指定键对应的值。如果该键存在于Map中，则返回与该键关联的值；如果该键不存在，则返回一个默认值(defaultValue)
			 */
			List<GoodsCategory> childList = parentChildMap.getOrDefault(parentId, new ArrayList<>());
			childList.add(category);
			parentChildMap.put(parentId, childList);
		}

		// 递归构建分类树
		List<GoodsCategory> rootCategory = new ArrayList<>();
		buildCategoryTree(0, rootCategory, categoryMap, parentChildMap);

		return rootCategory;
	}

	private void buildCategoryTree(int parentId, List<GoodsCategory> categoryList, Map<Integer, GoodsCategory> categoryMap, Map<Integer, List<GoodsCategory>> parentChildMap) {
		List<GoodsCategory> childList = parentChildMap.get(parentId);
		if (childList != null) {
			for (GoodsCategory category : childList) {
				categoryList.add(category);
				buildCategoryTree(category.getId(), category.getChild(), categoryMap, parentChildMap);
			}
		}
	}

	@Override
	public Page<Goods> pageSearchGoods(PageSearchGoodsParam param) {
		//计算分页开始索引
		int startIndex = (param.getCurrentPage() - 1) * param.getPageSize();

		//查询搜索商品总数量
		int totalCount = goodsMapper.pageSelectGoodsCount(param);

		Page<Goods> page = new Page<>();

		page.setCurrentPage(param.getCurrentPage());
		page.setPageSize(param.getPageSize());
		page.setTotalCount(totalCount);

		if (totalCount != 0) {
			page.setData(goodsMapper.pageSelectGoods(param, startIndex));
		}

		return page;
	}

	@Override
	public List<GoodsCategoryAttrs> getCategoryAttrs(Integer categoryId, String keyword) {
		List<Integer> categoryIdList = Optional.ofNullable(categoryId)
				.map(Collections::singletonList)
				.orElse(goodsMapper.selectCategoryIdByKeyword(keyword));

		List<GoodsCategoryAttrs> attrKeys = null;
		if (!categoryIdList.isEmpty()) {
			attrKeys = goodsMapper.selectGoodsCategoryAttrsByCategoryId(categoryIdList);
			if (!attrKeys.isEmpty()) {
				List<Integer> attrKeyIds = attrKeys.stream().map(GoodsCategoryAttrs::getId).collect(Collectors.toList());
				List<GoodsAttrs> attrValues = goodsMapper.selectGoodsAttrsByCategoryAttrId(attrKeyIds);
				Map<Integer, List<GoodsAttrs>> map = new HashMap<>();

				//构建key与value的映射
				for (GoodsAttrs attrValue : attrValues) {
					List<GoodsAttrs> orDefault = map.getOrDefault(attrValue.getCategoryAttrId(), new ArrayList<>());
					orDefault.add(attrValue);
					map.put(attrValue.getCategoryAttrId(), orDefault);
				}

				for (GoodsCategoryAttrs attrKey : attrKeys) {
					attrKey.setList(map.get(attrKey.getId()));
				}
			}
		}

		return attrKeys;
	}

	@Override
	public Goods getGoodsInfo(int goodsId) {
		//获取商品基础信息
		Goods goods = goodsMapper.selectGoodsInfo(goodsId);
		if (goods == null) {
			return new Goods();
		}

		List<GoodsCategorySaleAttrs> saleAttrsKey = goodsMapper.selectGoodsSaleAttrs(goodsId);
		List<GoodsCategorySaleAttrsValue> saleAttrsValue = goodsMapper.selectGoodsSaleAttrsValue(goodsId);
		Map<Integer, List<GoodsCategorySaleAttrsValue>> map = new HashMap<>();

		//构建keyId与value的映射
		for (GoodsCategorySaleAttrsValue value : saleAttrsValue) {
			List<GoodsCategorySaleAttrsValue> values = map.getOrDefault(value.getSaleAttrId(), new ArrayList<>());
			values.add(value);
			map.put(value.getSaleAttrId(), values);
		}

		//构建售卖信息
		for (GoodsCategorySaleAttrs key : saleAttrsKey) {
			List<GoodsCategorySaleAttrsValue> value = map.get(key.getId());
			if (value != null) {
				key.setValues(value);
			} else {
				key.setValues(new ArrayList<>());
			}
		}
		goods.setSaleAttrs(saleAttrsKey);

		//设置商品图片
		goods.setImgs(goodsMapper.selectGoodsImages(goodsId));

		//查询商品分类名称
		List<Integer> categoryIds = Arrays.asList(goods.getCategory1Id(), goods.getCategory2Id(), goods.getCategory3Id());
		goods.setCategoryName(goodsMapper.selectGoodsCategory(categoryIds));

		return goods;
	}
}
